package com.getpebble.android.framework.datalogging;

import android.content.ContentResolver;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Looper;
import com.getpebble.android.PebbleApplication;
import com.getpebble.android.common.core.trace.Trace;
import com.getpebble.android.common.model.PblDevice;
import com.getpebble.android.framework.analytics.WatchAnalytics;
import com.getpebble.android.framework.comm.MessageRouter;
import com.getpebble.android.framework.endpoint.EndpointRequest;
import com.getpebble.android.framework.endpoint.EndpointRequest.EndpointAction;
import com.getpebble.android.framework.endpoint.EndpointRequest.EndpointArgumentKeys;
import com.getpebble.android.framework.pebblekit.PebbleKit;
import com.getpebble.android.framework.protocol.EndpointId;
import com.getpebble.android.framework.protocol.inbound.PblInboundDataloggingMessage;
import com.getpebble.android.framework.protocol.inbound.PblInboundDataloggingMessage.Command;
import com.google.common.primitives.UnsignedInteger;
import com.sun.mail.imap.protocol.ListInfo;
import com.sun.mail.smtp.SMTPMessage;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.UUID;

public class Datalogging {
    private static final String TAG = Datalogging.class.getSimpleName();
    private static Datalogging sInstance;
    private final ContentResolver mContentResolver;
    private final DataloggingDb mDatabase;
    private final Handler mHandler;
    private final PebbleKit mPebbleKit;
    private final List<DataloggingSession> mSessions;

    static /* synthetic */ class AnonymousClass5 {
        static final /* synthetic */ int[] $SwitchMap$com$getpebble$android$framework$protocol$inbound$PblInboundDataloggingMessage$Command = new int[Command.values().length];

        static {
            try {
                $SwitchMap$com$getpebble$android$framework$protocol$inbound$PblInboundDataloggingMessage$Command[Command.OPEN_SESSION.ordinal()] = 1;
            } catch (NoSuchFieldError e) {
            }
            try {
                $SwitchMap$com$getpebble$android$framework$protocol$inbound$PblInboundDataloggingMessage$Command[Command.DATA.ordinal()] = 2;
            } catch (NoSuchFieldError e2) {
            }
            try {
                $SwitchMap$com$getpebble$android$framework$protocol$inbound$PblInboundDataloggingMessage$Command[Command.CLOSE_SESSION.ordinal()] = 3;
            } catch (NoSuchFieldError e3) {
            }
            try {
                $SwitchMap$com$getpebble$android$framework$protocol$inbound$PblInboundDataloggingMessage$Command[Command.TIMEOUT.ordinal()] = 4;
            } catch (NoSuchFieldError e4) {
            }
        }
    }

    Datalogging(DataloggingDb database, Looper looper, ContentResolver resolver, PebbleKit pebbleKit) {
        Trace.debug(TAG, "Datalogging()");
        if (database == null) {
            throw new IllegalArgumentException("database cannot be null");
        } else if (looper == null) {
            throw new IllegalArgumentException("looper cannot be null");
        } else if (resolver == null) {
            throw new IllegalArgumentException("resolver cannot be null");
        } else if (pebbleKit == null) {
            throw new IllegalArgumentException("pebbleKit cannot be null");
        } else {
            this.mHandler = new Handler(looper);
            this.mDatabase = database;
            this.mContentResolver = resolver;
            this.mPebbleKit = pebbleKit;
            this.mSessions = this.mDatabase.loadSessionsFromDatabase();
            Iterator<DataloggingSession> iterator = this.mSessions.iterator();
            while (iterator.hasNext()) {
                DataloggingSession session = (DataloggingSession) iterator.next();
                if (session.checkComplete()) {
                    this.mDatabase.deleteSessionRecord(session);
                    iterator.remove();
                }
            }
            handleClientRequestData(WatchAnalytics.WATCH_ANALYTICS_APP_UUID);
        }
    }

    public static synchronized Datalogging getInstance(Context context) {
        Datalogging datalogging;
        synchronized (Datalogging.class) {
            if (sInstance == null) {
                PebbleKit pebbleKit = PebbleKit.getInstance(context);
                DataloggingDb database = new DataloggingDb(context, pebbleKit);
                HandlerThread handlerThread = new HandlerThread("datalogging");
                handlerThread.start();
                sInstance = new Datalogging(database, handlerThread.getLooper(), context.getContentResolver(), pebbleKit);
            }
            datalogging = sInstance;
        }
        return datalogging;
    }

    public void handleWatchMessage(final PblInboundDataloggingMessage message) {
        Trace.debug(TAG, "handleWatchMessage()");
        if (message == null) {
            Trace.warning(TAG, "message is null");
        } else {
            this.mHandler.post(new Runnable() {
                public void run() {
                    Datalogging.this.handleWatchMessageInternal(message);
                }
            });
        }
    }

    public void handleClientAck(final UUID localSessionUuid, final int dataId) {
        Trace.verbose(TAG, "handleClientAck()");
        this.mHandler.post(new Runnable() {
            public void run() {
                Datalogging.this.handleClientAckInternal(localSessionUuid, dataId);
            }
        });
    }

    public void handleClientRequestData(final UUID appUuid) {
        Trace.verbose(TAG, "handleClientRequestData()");
        this.mHandler.post(new Runnable() {
            public void run() {
                Datalogging.this.handleClientRequestDataInternal(appUuid);
            }
        });
    }

    private void handleWatchMessageInternal(PblInboundDataloggingMessage message) {
        Trace.verbose(TAG, "handleWatchMessageInternal()");
        switch (AnonymousClass5.$SwitchMap$com$getpebble$android$framework$protocol$inbound$PblInboundDataloggingMessage$Command[message.getCommand().ordinal()]) {
            case SMTPMessage.RETURN_FULL /*1*/:
                openSession(message);
                return;
            case SMTPMessage.RETURN_HDRS /*2*/:
                receiveData(message);
                return;
            case ListInfo.INDETERMINATE /*3*/:
                closeSession(message);
                return;
            case SMTPMessage.NOTIFY_DELAY /*4*/:
                sendOpenSesionsReport();
                return;
            default:
                return;
        }
    }

    private void sendOpenSesionsReport() {
        Trace.debug(TAG, "sendOpenSesionsReport()");
        List<UnsignedInteger> openSessionIds = new LinkedList();
        for (DataloggingSession session : this.mSessions) {
            if (!session.isFinished()) {
                openSessionIds.add(session.getSessionId());
            }
        }
        if (openSessionIds.size() != 0) {
            int[] intOpenSessionIds = new int[openSessionIds.size()];
            for (int i = 0; i < openSessionIds.size(); i++) {
                intOpenSessionIds[i] = ((UnsignedInteger) openSessionIds.get(i)).intValue();
            }
            Bundle bundle = new Bundle();
            bundle.putIntArray(EndpointArgumentKeys.DATALOGGING_SESSIONS.toString(), intOpenSessionIds);
            sendRequestToConnectedWatch(new EndpointRequest(EndpointId.DATA_LOG, EndpointAction.SEND_DATALOGGING_REPORT_OPEN_SESSIONS, bundle));
        }
    }

    private void handleClientAckInternal(UUID localSessionUuid, int dataId) {
        Trace.verbose(TAG, "handleClientAckInternal()");
        DataloggingSession session = findSessionWithLocalUuid(localSessionUuid);
        if (session == null) {
            Trace.warning(TAG, "handleClientAckInternal(): session not found for local UUID = " + localSessionUuid);
        } else {
            session.ackItem(dataId);
        }
    }

    private void handleClientRequestDataInternal(UUID appUuid) {
        Trace.debug(TAG, "handleClientRequestDataInternal()");
        if (appUuid == null) {
            Trace.warning(TAG, "handleClientRequestDataInternal(): appUuid is null");
            return;
        }
        for (DataloggingSession session : this.mSessions) {
            if (appUuid.equals(session.getAppUuid())) {
                session.broadcastData();
            }
        }
    }

    private boolean sendAckToWatch(UnsignedInteger sessionId) {
        Trace.debug(TAG, "sendAckToWatch() sessionId = " + sessionId);
        if (sessionId == null) {
            Trace.warning(TAG, "sendAckToWatch(): sessionId is null");
            return false;
        }
        Bundle args = new Bundle();
        args.putInt(EndpointArgumentKeys.DATALOGGING_SESSION.toString(), sessionId.intValue());
        return sendRequestToConnectedWatch(new EndpointRequest(EndpointId.DATA_LOG, EndpointAction.SEND_DATALOGGING_ACK, args));
    }

    private void sendNackToWatch(UnsignedInteger sessionId) {
        Trace.debug(TAG, "sendNackToWatch() sessionId = " + sessionId);
        if (sessionId == null) {
            Trace.warning(TAG, "sendNackToWatch(): sessionId is null");
            return;
        }
        Bundle args = new Bundle();
        args.putInt(EndpointArgumentKeys.DATALOGGING_SESSION.toString(), sessionId.intValue());
        sendRequestToConnectedWatch(new EndpointRequest(EndpointId.DATA_LOG, EndpointAction.SEND_DATALOGGING_NACK, args));
    }

    protected boolean sendRequestToConnectedWatch(EndpointRequest request) {
        PblDevice device = PebbleApplication.getConnectedDevice();
        if (device == null) {
            Trace.debug(TAG, "Can't send Ack to watch: no connected device");
            return false;
        }
        MessageRouter router = MessageRouter.getRouter(device);
        if (router == null) {
            return false;
        }
        Trace.debug(TAG, "Sending " + request.getAction() + " request to " + device);
        return router.onRequest(request, null);
    }

    private void openSession(PblInboundDataloggingMessage message) {
        if (message == null) {
            Trace.warning(TAG, "openSession(): message is null");
            return;
        }
        Trace.debug(TAG, "openSession() id = " + message.getSessionId());
        boolean addNewSession = true;
        try {
            DataloggingSession session = findOpenSessionWithId(message.getSessionId());
            if (session != null) {
                if (session.matchesSessionParameters(message)) {
                    Trace.debug(TAG, "Found open session with matching parameters id = " + message.getSessionId());
                    addNewSession = false;
                } else {
                    Trace.debug(TAG, "Found open session with mismatched parameters id = " + message.getSessionId());
                    session.close();
                }
            }
            if (addNewSession) {
                Trace.debug(TAG, "addNewSession id = " + message.getSessionId());
                this.mSessions.add(new DataloggingSession(message, this.mDatabase, this.mPebbleKit));
            }
            sendAckToWatch(message.getSessionId());
        } catch (Exception e) {
            Trace.warning(TAG, "Error opening session: sending nack", e);
            sendNackToWatch(message.getSessionId());
        }
    }

    /* JADX WARNING: inconsistent code. */
    /* Code decompiled incorrectly, please refer to instructions dump. */
    private void receiveData(com.getpebble.android.framework.protocol.inbound.PblInboundDataloggingMessage r10) {
        /*
        r9 = this;
        r6 = TAG;
        r7 = "receiveData()";
        com.getpebble.android.common.core.trace.Trace.debug(r6, r7);
        if (r10 != 0) goto L_0x0011;
    L_0x0009:
        r6 = TAG;
        r7 = "receiveData(): message is null";
        com.getpebble.android.common.core.trace.Trace.warning(r6, r7);
    L_0x0010:
        return;
    L_0x0011:
        r6 = r10.getSessionId();
        r5 = r9.findOpenSessionWithId(r6);
        if (r5 != 0) goto L_0x003f;
    L_0x001b:
        r6 = TAG;
        r7 = new java.lang.StringBuilder;
        r7.<init>();
        r8 = "receiveData(): open session not found with ID = ";
        r7 = r7.append(r8);
        r8 = r10.getSessionId();
        r7 = r7.append(r8);
        r7 = r7.toString();
        com.getpebble.android.common.core.trace.Trace.info(r6, r7);
        r6 = r10.getSessionId();
        r9.sendNackToWatch(r6);
        goto L_0x0010;
    L_0x003f:
        r6 = r9.mDatabase;	 Catch:{ InvalidPayloadException -> 0x0077, SQLException -> 0x009a }
        r6.beginTransaction();	 Catch:{ InvalidPayloadException -> 0x0077, SQLException -> 0x009a }
        r6 = r5.getDataType();	 Catch:{ InvalidPayloadException -> 0x0077, SQLException -> 0x009a }
        r7 = r5.getItemSize();	 Catch:{ InvalidPayloadException -> 0x0077, SQLException -> 0x009a }
        r2 = r10.getDataPayload(r6, r7);	 Catch:{ InvalidPayloadException -> 0x0077, SQLException -> 0x009a }
        r1 = r5.addData(r2);	 Catch:{ InvalidPayloadException -> 0x0077, SQLException -> 0x009a }
        r6 = r5.getSessionId();	 Catch:{ InvalidPayloadException -> 0x0077, SQLException -> 0x009a }
        r6 = r9.sendAckToWatch(r6);	 Catch:{ InvalidPayloadException -> 0x0077, SQLException -> 0x009a }
        if (r6 == 0) goto L_0x008c;
    L_0x005e:
        r6 = r9.mDatabase;	 Catch:{ InvalidPayloadException -> 0x0077, SQLException -> 0x009a }
        r6.setTransactionSuccessful();	 Catch:{ InvalidPayloadException -> 0x0077, SQLException -> 0x009a }
        r4 = r1.iterator();	 Catch:{ InvalidPayloadException -> 0x0077, SQLException -> 0x009a }
    L_0x0067:
        r6 = r4.hasNext();	 Catch:{ InvalidPayloadException -> 0x0077, SQLException -> 0x009a }
        if (r6 == 0) goto L_0x0093;
    L_0x006d:
        r0 = r4.next();	 Catch:{ InvalidPayloadException -> 0x0077, SQLException -> 0x009a }
        r0 = (com.getpebble.android.framework.datalogging.DataloggingItem) r0;	 Catch:{ InvalidPayloadException -> 0x0077, SQLException -> 0x009a }
        r0.broadcast();	 Catch:{ InvalidPayloadException -> 0x0077, SQLException -> 0x009a }
        goto L_0x0067;
    L_0x0077:
        r3 = move-exception;
        r6 = TAG;	 Catch:{ all -> 0x00b0 }
        r7 = "Invalid payload: sending nack";
        com.getpebble.android.common.core.trace.Trace.warning(r6, r7, r3);	 Catch:{ all -> 0x00b0 }
        r6 = r5.getSessionId();	 Catch:{ all -> 0x00b0 }
        r9.sendNackToWatch(r6);	 Catch:{ all -> 0x00b0 }
        r6 = r9.mDatabase;
        r6.endTransaction();
        goto L_0x0010;
    L_0x008c:
        r6 = TAG;	 Catch:{ InvalidPayloadException -> 0x0077, SQLException -> 0x009a }
        r7 = "Ack not sent: transaction will be rolled back";
        com.getpebble.android.common.core.trace.Trace.warning(r6, r7);	 Catch:{ InvalidPayloadException -> 0x0077, SQLException -> 0x009a }
    L_0x0093:
        r6 = r9.mDatabase;
        r6.endTransaction();
        goto L_0x0010;
    L_0x009a:
        r3 = move-exception;
        r6 = TAG;	 Catch:{ all -> 0x00b0 }
        r7 = "Error inserting: sending nack";
        com.getpebble.android.common.core.trace.Trace.warning(r6, r7, r3);	 Catch:{ all -> 0x00b0 }
        r6 = r5.getSessionId();	 Catch:{ all -> 0x00b0 }
        r9.sendNackToWatch(r6);	 Catch:{ all -> 0x00b0 }
        r6 = r9.mDatabase;
        r6.endTransaction();
        goto L_0x0010;
    L_0x00b0:
        r6 = move-exception;
        r7 = r9.mDatabase;
        r7.endTransaction();
        throw r6;
        */
        throw new UnsupportedOperationException("Method not decompiled: com.getpebble.android.framework.datalogging.Datalogging.receiveData(com.getpebble.android.framework.protocol.inbound.PblInboundDataloggingMessage):void");
    }

    private void closeSession(PblInboundDataloggingMessage message) {
        Trace.debug(TAG, "closeSession()");
        if (message == null) {
            Trace.warning(TAG, "closeSession(): message is null");
            return;
        }
        sendAckToWatch(message.getSessionId());
        DataloggingSession session = findOpenSessionWithId(message.getSessionId());
        if (session == null) {
            Trace.info(TAG, "closeSession(): open session not found with ID = " + message.getSessionId());
        } else {
            session.close();
        }
    }

    private DataloggingSession findOpenSessionWithId(UnsignedInteger sessionId) {
        for (DataloggingSession session : this.mSessions) {
            if (session.getSessionId().equals(sessionId) && !session.isFinished()) {
                return session;
            }
        }
        return null;
    }

    private DataloggingSession findSessionWithLocalUuid(UUID localSessionUuid) {
        for (DataloggingSession session : this.mSessions) {
            if (session.getLocalSessionUuid().equals(localSessionUuid)) {
                return session;
            }
        }
        return null;
    }
}
